<?php

class TournamentregistrationsPage extends BaseAdminPage {

	/**
	 * A verseny azonosítója.
	 *
	 * @var int
	 */
	private $tournamentId;

	function TournamentregistrationsPage() {
		parent::BaseAdminPage('TournamentregistrationsPage');
	}

	function enterPage() {
		parent::enterPage();

		// definiáljuk a form elemeit (ezek kamu mezők, csak a FormUtil kihasználása miatt vannak)
		FormUtil::addForm("tournamentregistration");
		FormUtil::addFormElement("tournamentregistration", new FormElementInfo("id_registration", "text"));
		FormUtil::addFormElement("tournamentregistration", new FormElementInfo("name", "text"));
		FormUtil::addFormElement("tournamentregistration", new FormElementInfo("email", "text"));
		FormUtil::addFormElement("tournamentregistration", new FormElementInfo("properties", "text"));
		FormUtil::resetFormValues("tournamentregistration");

		$this->tournamentId = FunctionLibrary::getGetValueSmart('id', null);
		$_SESSION['__tournamentId'] = $this->tournamentId;
	}

	function leavePage() {
		parent::leavePage();
			
		FormUtil::removeAllForms();

		unset($_SESSION['__tournamentId']);
	}

	protected function _init() {
		$this->tournamentId = FunctionLibrary::getSessionValue('__tournamentId', null);
	}

	public function serveRequest() {
		parent::serveRequest();

		$this->_init();

		$tpl = BaseAdminPage::loadTemplateFile("tournamentregistrations.tpl.html");
		TextHandler::insertTextsIntoTemplate($tpl, null, 'compr_');

		$tpl->setVariable('app_root_url', APP_ROOT_URL);

		$ttypes = AdminDBHelper::getTournamentTypes(TextHandler::getCurrentLangcode());
		$ttypes = TournamentHandler::getTournamentTypesForCombo($ttypes);
		$records = SiteDBHelper::getTournamentRegistrations($this->tournamentId);
		if(is_null($records)) {
			// suxxx!
			handleError(TextHandler::getText('err_readrecordsfailed'));
			$tpl->replaceBlock('tournamenttypes', ' ', false);
			$tpl->touchBlock('tournamenttypes');
		} else {
			// megvannak a rekordok!
			$action = FunctionLibrary::getGetValue('action');
			if($action) {
				$action = 'action_'.$action;
				$this->$action();
			}

			if(count($records) == 0) {
				$tpl->replaceBlock('tournamenttypes', ' ', false);
				$tpl->touchBlock('tournamenttypes');
				$tpl->replaceBlock('tournamentemailall', ' ', false);
				$tpl->touchBlock('tournamentemailall');
			} else {
				$prevTType = -1;
				$counter = 0;
				$allEmail = array('default' => array());
				$tournament = SiteDBHelper::getTournament($this->tournamentId, TextHandler::getCurrentLangcode());
				foreach($records as $record) {
					$regTpl = BaseAdminPage::loadTemplateFile("tournamentregistration.tpl.html");
					$regTpl->setVariable('app_root_url', APP_ROOT_URL);
					if ($prevTType != $record['id_tournamenttype']) {
						if ($prevTType > 0) {
							$tpl->setVariable('registrationsHtml', $registrationHtml->toString());
							$tpl->parseCurrentBlock();
						}
						$tpl->setCurrentBlock('tournamenttypes');
						$tpl->setVariable('tournamenttype', $ttypes[$record['id_tournamenttype']]);
						$tpl->setVariable('compr_field_serial', TextHandler::getText('compr_field_serial'));
						$tpl->setVariable('compr_field_players', TextHandler::getText('compr_field_players'));
						$tpl->setVariable('tblhead_opers', TextHandler::getText('tblhead_opers'));
						$prevTType = $record['id_tournamenttype'];
						$registrationHtml = new StringBuffer();
						$counter = 0;
					}

					$trClasses = ($counter++ % 2? array('odd'): array());
	
					$regTpl->setVariable("link_del", HydraLinkProvider::getLink("delTournamentRegistration", array("id" => $record['id'])));
					$regTpl->setVariable("link_addPlayer", HydraLinkProvider::getLink("addTournamentRegistrationPlayer", array("id" => $record['id'])));
					$regTpl->setVariable("tr_class", implode($trClasses, " "));
					$regTpl->setVariable('app_root_url', APP_ROOT_URL);
					$regTpl->setVariable('but_delete', TextHandler::getText('but_delete'));
					$regTpl->setVariable('but_add', TextHandler::getText('but_add'));
					$regTpl->setVariable('compr_del_confirm', TextHandler::getText('compr_del_confirm'));

					$regTpl->setVariable("id", $record['id']);
					$regTpl->setVariable("serial", $counter);

					$players = array();
					foreach ($record['players'] as $playerId => $player) {
						if(FormUtil::hasFormInstance("tournamentregistration", $playerId)) {
							// szerkesztés alatt áll
							$regPlayerTplFile = "tournamentregistration_edit.tpl.html";
						} else {
							// nem áll szerkesztés alatt
							$regPlayerTplFile = "tournamentregistration_raw.tpl.html";
						}
						$regPlayerTpl = BaseAdminPage::loadTemplateFile($regPlayerTplFile);
						$regPlayerTpl->setVariable('app_root_url', APP_ROOT_URL);

						if (FormUtil::hasFormInstance("tournamentregistration", $playerId)) {
							$values = FormUtil::getFormValues("tournamentregistration", $playerId);
							$fieldsTpl = TournamentHandler::getTournamentRegistrationFields($tournament, $values);
							$regPlayerTpl->setVariable("fields", $fieldsTpl->get());
							TextHandler::insertTextsIntoTemplate($regPlayerTpl);
							
							$regPlayerTpl->setVariable("formAction", HydraLinkProvider::getLink("modTournamentRegistrationPlayer", array("id" => $playerId)));
							$regPlayerTpl->setVariable("link_cancel", HydraLinkProvider::getLink("cancelEditTournamentRegistrationPlayer", array("id" => $playerId)));
							$regPlayerTpl->setVariable('but_modify', TextHandler::getText('but_modify'));
							$regPlayerTpl->setVariable('but_cancel', TextHandler::getText('but_cancel'));
						} else {
							$regPlayerTpl->setVariable("playerInfo", $player);
							$regPlayerTpl->setVariable('but_delete', TextHandler::getText('but_delete'));
							$regPlayerTpl->setVariable('compr_del_confirm', TextHandler::getText('compr_del_confirm'));
							$regPlayerTpl->setVariable('but_edit', TextHandler::getText('but_edit'));
							$regPlayerTpl->setVariable("link_delPlayer", HydraLinkProvider::getLink("delTournamentRegistrationPlayer", array("id" => $playerId)));
							$regPlayerTpl->setVariable("link_editPlayer", HydraLinkProvider::getLink("editTournamentRegistrationPlayer", array("id" => $playerId)));
						}
						$players[] = $regPlayerTpl->get();
						foreach ($record['emails'] as $playerId => $email) {
							$email = preg_replace('/\s|,/', '', $email);
							if (isset($record['langcodes'][$playerId])) {
								if (! isset($allEmail[$record['langcodes'][$playerId]])) {
									$allEmail[$record['langcodes'][$playerId]] = array();
								}
								$allEmail[$record['langcodes'][$playerId]][] = $email;
							} else {
								$allEmail['default'][] = $email;
							}
						}
					}
					$regTpl->setVariable('players', implode('', $players));	
					$registrationHtml->append($regTpl->get());
				}
				if ($prevTType > 0) {
					$tpl->setVariable('registrationsHtml', $registrationHtml->toString());
					$tpl->parseCurrentBlock();
				}
				foreach ($allEmail as $langcode => $emails) {
					$emails = array_unique($emails);
					$counter = 0;
					while (count($emails) > 0) {
						$tpl->setCurrentBlock('tournamentemailall');
						$currentEmails = array_splice($emails, 0, 20);
						$tpl->setVariable('mailto_href', implode(',', $currentEmails));
						$group = ++$counter;
						if ($langcode != 'default') $group .= '/'.$langcode;
						$tpl->setVariable('compr_emailall', TextHandler::getParsedText('compr_emailall', array('group' => $group)));
						$tpl->parseCurrentBlock();
					}
				}
				$tpl->setVariable('exportLink', HydraLinkProvider::getLink('exportTournamentRegistrations'));
			}
		}

		return $tpl->get();
	}

	/**
	 * Töröl.
	 */
	private function action_delTournamentRegistration() {
		AdminPageHelper::action_del('delTournamentRegistration', 'tournamentregistration', "compr_del_success", "compr_del_err", "link_tournamentregistration");
	}

	/**
	 * Új játékos hozzáadása.
	 */
	private function action_addTournamentRegistrationPlayer() {
		$errorStrings = array(TextHandler::getText('err_unknown'));
		$logErrorString = null;

		$errorLinkKey = HydraLinkProvider::getLink('link_tournamentregistration');

		$id = FunctionLibrary::getGetOrPostValueSmart('id', null);
		try {
			$formValues = array(
				'id_registration' => $id,
				'name' => TextHandler::getText('compr_field_name_default')
			);

			$playerId = AdminDBHelper::addTournamentRegistrationPlayer($formValues);
			$successLinkKey = HydraLinkProvider::getLink('editTournamentRegistrationPlayer', array('id' => $playerId));

			handleSuccess(TextHandler::getText('compr_add_success'), $successLinkKey."#row_$id");
			exit();
		} catch (ParameterException $e) {
			$errorStrings = $e->getErrors();
		} catch (Exception $e) {
			$logErrorString = "adding registration_player failed";
			Log::error('following errors occured during operation: '.$logErrorString);
			$errorStrings = array($e->getMessage());
		}

		handleError(TextHandler::getParsedText('compr_add_err', array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), $errorLinkKey);
		exit();
	}

	/**
	 * Szerkeszt.
	 */
	private function action_editTournamentRegistrationPlayer() {
		$id = FunctionLibrary::getGetValue('id');
		$record = AdminDBHelper::getTournamentRegistrationPlayer($id);
		AdminPageHelper::action_edit('tournamentregistration', $record, HydraLinkProvider::getLink("link_tournamentregistration")."#row_$id", false);
		handleSuccess("", HydraLinkProvider::getLink("link_tournamentregistration")."#row_".$record['id_registration']);
		exit();
	}

	/**
	 * Szerkesztés visszavonása.
	 */
	private function action_cancelTournamentRegistrationPlayer() {
		AdminPageHelper::action_cancel('tournamentregistration', "link_tournamentregistration");
	}

	/**
	 * Módosít.
	 */
	private function action_modTournamentRegistrationPlayer() {
		$errorStrings = array(TextHandler::getText('err_unknown'));
		$logErrorString = null;

		$successLinkKey = $errorLinkKey = HydraLinkProvider::getLink('link_tournamentregistration');

		$id = FunctionLibrary::getGetOrPostValueSmart('id', null);
		if(!empty($id) && is_numeric($id)) {
			$id = intval($id);

			// próbáljuk frissíteni!
			try {
				// adatok összerakása
				$names = FunctionLibrary::getPostValue('names');
				$emails = FunctionLibrary::getPostValue('emails');
				$tournament = SiteDBHelper::getTournament($this->tournamentId, TextHandler::getCurrentLangcode());
				$regData = AdminDBHelper::getRegistrationByPlayerId($id);
				$regTime = DBUtil::parseDBFormattedTimestamp($regData['created_at']);
				$tournamentType = $regData['id_tournamenttype'];
				$properties = TournamentHandler::getTournamentRegistrationData($tournament, $tournamentType, $regTime);
				$realValues = array(
					'id' => $id,
					'name' => $names[0],
					'email' => $emails[0],
					'properties' => json_encode($properties[0])
				);
				
				$this->checkData('mod', $realValues);

				AdminDBHelper::modTournamentRegistrationPlayer($realValues);

				// email küldés
				$site = SiteHandler::getCurrentSite();
				$variables = array(
					'comp' => $tournament['name'],
					'siteName' => $site->name
				);
				$recipients = TournamentHandler::getRecipientsForTournamentRegistrationEmail($names, $emails, $properties, $tournamentType);

				AlertHandler::sendEmailAlert('tournament_registration_modified.tpl.email', $recipients, $variables);
				
				// kidobjuk a form instance-át!
				FormUtil::removeFormInstanceIfExists('tournamentregistration', $id);
				handleSuccess(TextHandler::getText('compr_mod_success'), $successLinkKey."#row_".$regData['id']);
				exit();
			} catch (ParameterException $e) {
				$errorStrings = $e->getErrors();
			} catch (Exception $e) {
				$logErrorString = "updating registration_player id=$id failed";
				Log::error('following errors occured during operation:'.$logErrorString);
				$errorStrings = array($e->getMessage());
			}
		} else {
			// na hát ez azért fura lenne...
			$logErrorString = "required request parameter 'id' is missing or not number";
			Log::error('following errors occured during operation:'.$logErrorString);
			$errorStrings = array(TextHandler::getText("err_unknown"));
		}

		handleError(TextHandler::getParsedText('compr_mod_err', array('errors'=>TextUtil::arrayToHtmlList($errorStrings))), $errorLinkKey);
		exit();
	}

	/**
	 * Töröl.
	 */
	private function action_delTournamentRegistrationPlayer() {
		AdminPageHelper::action_del('delTournamentRegistrationPlayer', 'tournamentregistration', "compr_del_success", "compr_del_err", "link_tournamentregistration");
	}

	public function checkData($type, $values) {
	}

	/**
	 * Jelentkezések exportálása.
	 */
	private function action_exportTournamentRegistrations() {
		$xls = null;
		$devErrors = array();

		try {
			ini_set('memory_limit', '256M');

			$tournament = SiteDBHelper::getTournament($this->tournamentId, TextHandler::getCurrentLangcode());
			$tournamentTypes = SiteDBHelper::getTournamentTypesOfTournament($this->tournamentId, TextHandler::getCurrentLangcode());
			$tournamentConfiguration = TournamentHandler::getTournamentConfiguration($tournament);

			$filename = "registrations_".date("Y-m-d", time()).".xls";
			$xls = new Spreadsheet_Excel_Writer();
			$xls->send($filename);

			$headerFormat =& $xls->addFormat();
			$headerFormat->setBold(1);
			$headerFormat->setHAlign("left");

			foreach ($tournamentTypes as $tournamentType) {
				$xlsSheet =& $xls->addWorksheet(TextUtil::toLatin2($tournamentType['name']));

				// fejléc
				$col = 0;
				$xlsSheet->writeString(0,$col++,TextUtil::toLatin2(TextHandler::getText("compr_export_header_serial")), $headerFormat);
				$xlsSheet->writeString(0,$col++,TextUtil::toLatin2(TextHandler::getText("compr_export_header_name")), $headerFormat);
				$xlsSheet->writeString(0,$col++,TextUtil::toLatin2(TextHandler::getText("compr_export_header_email")), $headerFormat);
				$fields = array();
				foreach ($tournamentConfiguration as $key => $value) {
					if (! is_bool($value)) {
						if ($key == 'calculation') $key = 'fee';
						$xlsSheet->writeString(0,$col++,TextUtil::toLatin2(TextHandler::getText("compr_export_header_$key")), $headerFormat);
					}
				}

				$row = 0;
				$registrations = AdminDBHelper::getTournamentRegistrationPlayers($this->tournamentId, $tournamentType['id'], "id ASC");
				foreach ($registrations as $registration) {
					$col = 0;
					$row++;
					$xlsSheet->writeString($row,$col++, $row);
					$xlsSheet->writeString($row,$col++, TextUtil::toLatin2($registration['name']));
					$xlsSheet->writeString($row,$col++, $registration['email']);
					$properties = json_decode($registration['properties']);
					if (! empty($properties)) {
						foreach ($tournamentConfiguration as $key => $value) {
							if (! is_bool($value)) {
								if (TextUtil::startsWith($key, 'field_')) {
									$fieldName = substr($key, strlen('field_'));
									$text = TextHandler::getText($value[$properties->$fieldName]);
								} else {
									if ($key == 'calculation') $key = 'fee';
									$text = null;
								}
								if (empty($text) && isset($properties->$key)) $text = $properties->$key;
								$xlsSheet->writeString($row,$col++, TextUtil::toLatin2($text));
							}
						}
					}
				}
			}

			// Finish the spreadsheet, dumping it to the browser
			if(!is_null($xls)) $xls->close();
		} catch (Exception $e) {
			handleError(TextHandler::getParsedText('compr_export_err', array('errors'=>$e->getMessage())), HydraLinkProvider::getLink('link_tournamentregistration'));
		}
		exit();
	}

}
